

<template>
  <div class="main-map-bg">
    <div id="data-analysis-map" style="height:100%"></div>
  </div>
</template>


 <script type="text/javascript">
import BMap from "BMap";
export default {
  name: "baiduMapDataAnalysis",
  data() {
    return {
      districtLoading: 0, //百度地图区域化个数
      blist: [], //百度地图遮罩集合
      deviceMarker: [], //用于存放旧的设备点的坐标，在请求之后，清除原来的点
      drivceLists: [],
      drivceList: [],
      heatmapOverlay: "", //热力图·
      pointsArray: [], //热力图的点
      devicePoint: [], //热力图的点（未加权重的集合）
      taskOfAddMarket: "", //添加点的任务
      appKey: ""
    };
  },
  methods: {
    /* ***************初始化百度地圖begin**************   */
    initDataAnalysisBaiduMap: function() {
      var map = new BMap.Map("data-analysis-map", { enableMapClick: false });
     map.centerAndZoom(new BMap.Point(114.77778,32.089846), 10);
      // map.centerAndZoom("信阳市",10); 
      map.enableScrollWheelZoom();
      map.disableDoubleClickZoom(); //禁止双击缩放
      map.enableScrollWheelZoom(true);
      this.addDistrict("信阳");
      //渲染个性化百度地图
      addindividuation(map);
      var _this = this;

      window.AnalysisBaiduMap = map; //将map变量储存在全局
      // 监听放大缩小事件 结束
      map.addEventListener("zoomend", function() {
        var u = window.AnalysisBaiduMap.getZoom();
        if (u > 12) {
          _this.closeHeatmap(); // 关闭热力图
          for (var i = 0; i < _this.deviceMarker.length; i++) {
            window.AnalysisBaiduMap.addOverlay(_this.deviceMarker[i]);
          }
        } else {
          for (var i = 0; i < _this.deviceMarker.length; i++) {
            window.AnalysisBaiduMap.removeOverlay(_this.deviceMarker[i]);
          }
          _this.openHeatmap(); // 开启热力图
        }
      });
    },
    /* ***************初始化百度地圖end**************   */
    /* ***************区域化百度地圖begin**************   */
    addDistrict: function(districtName) {
      var _this = this;
      //使用计数器来控制加载过程
      _this.districtLoading++;
      var bdary = new BMap.Boundary();

      bdary.get(districtName, function(rs) {
        //获取行政区域
        var count = rs.boundaries.length; //行政区域的点有多少个
        if (count === 0) {
          alert("未能获取当前输入行政区域");
          return;
        }
        for (var i = 0; i < count; i++) {
          _this.blist.push({ points: rs.boundaries[i], name: districtName });
        }
        //加载完成区域点后计数器-1
        _this.districtLoading--;
        if (_this.districtLoading == 0) {
          //全加载完成后画端点
          _this.drawBoundary();
        }
      });
    },
    drawBoundary: function() {
      var _this = this;
      //包含所有区域的点数组
      var pointArray = [];

      /*画遮蔽层的相关方法
       *思路: 首先在中国地图最外画一圈，圈住理论上所有的中国领土，然后再将每个闭合区域合并进来，并全部连到西北角。
       *      这样就做出了一个经过多次西北角的闭合多边形*/

      //定义中国东南西北端点，作为第一层
      var pNW = { lat: 59.0, lng: 73.0 };
      var pNE = { lat: 59.0, lng: 136.0 };
      var pSE = { lat: 3.0, lng: 136.0 };
      var pSW = { lat: 3.0, lng: 73.0 };
      //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
      var pArray = [];
      pArray.push(pNW);
      pArray.push(pSW);
      pArray.push(pSE);
      pArray.push(pNE);
      pArray.push(pNW);
      //循环添加各闭合区域
      for (var i = 0; i < this.blist.length; i++) {
        //添加显示用标签层
        var label = new BMap.Label(this.blist[i].name, {
          offset: new BMap.Size(20, -10)
        });
        label.hide();
        window.AnalysisBaiduMap.addOverlay(label);

        //添加多边形层并显示
        var ply = new BMap.Polygon(this.blist[i].points, {
          strokeWeight: 3,
          strokeColor: "#1157a4",
          fillOpacity: 0.01,
          fillColor: " #FFFFFF"
        }); //建立多边形覆盖物
        /**
         * 各种鼠标事件绑定
         */
        function click(evt) {
          for (var i = 0; i < _this.deviceMarker.length; i++) {
            _this.deviceMarker[i].closeInfoWindow();
          }
        }
        function mouseover(evt) {}
        function mousemove(evt) {}
        function mouseout(evt) {}

        ply.name = this.blist[i].name;
        ply.label = label;
        ply.addEventListener("click", click);
        ply.addEventListener("mouseover", mouseover);
        ply.addEventListener("mouseout", mouseout);
        ply.addEventListener("mousemove", mousemove);
        window.AnalysisBaiduMap.addOverlay(ply);

        //添加名称标签层
        //  var centerlabel = new BMap.Label(blist[i].name, { offset: new BMap.Size(0, 0) });
        // centerlabel.setPosition(ply.getBounds().getCenter());
        //  map.addOverlay(centerlabel);

        //将点增加到视野范围内
        var path = ply.getPath();
        pointArray = pointArray.concat(path);
        //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
        pArray = pArray.concat(path);
        pArray.push(pArray[0]);
      }

      //限定显示区域，需要引用api库
      var boundply = new BMap.Polygon(pointArray);
      // BMapLib.AreaRestriction.setBounds(map, boundply.getBounds());
      // window.AnalysisBaiduMap.setViewport(pointArray); //调整视野

      //添加遮蔽层
      var plyall = new BMap.Polygon(pArray, {
        strokeOpacity: 0.0000001,
        strokeColor: "#000000",
        strokeWeight: 0.00001,
        fillColor: "#ffffff",
        fillOpacity: 1
      }); //建立多边形覆盖物
      //  map.addOverlay(plyall);
    },

    /* ***************区域化百度地圖end**************   */

    /* ***************创建百度地图点的坐标加信息框begin**************   */
    createMarket: function(node, info_html) {
      var myIcon = new BMap.Icon(
        "static/img/icon_drivce_small.png",
        new BMap.Size(37, 45)
      );
      var marker = new BMap.Marker(new BMap.Point(node.lng, node.lat), {
        icon: myIcon
      });
      var opts = {
        width: 200, // 信息窗口宽度
        height: 100, // 信息窗口高度
        title: "<div>设备信息</div>", // 信息窗口标题
        enableMessage: true, //设置允许信息窗发送短息
        message: "设备信息message"
      };

      marker.addEventListener("mouseover", function(e) {
        var myIcon = new BMap.Icon(
          "static/img/icon_drivce_big.png",
          new BMap.Size(54, 67)
        );
        marker.setIcon(myIcon);
        //  this.openInfoWindow(new BMap.InfoWindow(info_html, opts));
      });
      marker.addEventListener("mouseout", function(e) {
        var myIcon = new BMap.Icon(
          "static/img/icon_drivce_small.png",
          new BMap.Size(37, 45)
        );
        marker.setIcon(myIcon);
        // this.closeInfoWindow();
      });

      marker.addEventListener("click", function(e) {
        this.openInfoWindow(new BMap.InfoWindow(info_html, opts));
      });
      return marker;
    },
    /* ***************创建百度地图点的坐标加信息框end**************   */

    /* ***************从后台读取设备点的信息begin**************   */
    //获取设备信息
    addMarketToMap: function(lng, lat, radius) {
      var _this = this;
      var drivceList = [];
      $.ajax({
        url: _this.global.heatData, //请求的url地址
        dataType: "json", //返回格式为json
        data: {
          "points[0].lng": lng,
          "points[0].lat": lat,
          "points[0].radius": radius,
          appKey: _this.appKey
        }, //参数值
        type: "POST", //请求方式
        beforeSend: function() {
          //请求前的处理
        },
        success: function(req) {
          if (req.code == "200") {
            if (_this.isEmptyObject(_this.deviceMarker)) {
              console.log("返回值为空");
            } else {
              for (var i = 0; i < _this.deviceMarker.length; i++) {
                window.AnalysisBaiduMap.removeOverlay(_this.deviceMarker[i]);
              }
            }
            _this.deviceMarker = [];
            _this.devicePoint = [];
            if (_this.isEmptyObject(req.data.points)) {
              console.log("返回数组为空");
            } else {
              for (var j = 0; j < req.data.points.length; j++) {
                var point = new BMap.Point(
                  req.data.points[j].lng,
                  req.data.points[j].lat
                );
                var reliJson = {
                  lng: req.data.points[j].lng,
                  lat: req.data.points[j].lat,
                  count: req.data.points[j].weight
                };
                _this.devicePoint.push(reliJson);
                var marker = _this.createMarket(point, "");

                var u = window.AnalysisBaiduMap.getZoom();
                if (u > 12) {
                  //缩放为10级时 展示点  否则展示热力图
                  window.AnalysisBaiduMap.addOverlay(marker);
                } else {
                  _this.openHeatmap();
                }

                _this.deviceMarker.push(marker); //把market放入集合
              }
            }
          }
        },
        complete: function() {
          //请求完成的处理
        },
        error: function() {
          //请求出错处理
          window.clearInterval(this.taskOfAddMarket);
        }
      });
    },
    /* ***************从后台读取设备点的信息end**************   */

    //判断浏览区是否支持canvas
    isSupportCanvas: function() {
      var elem = document.createElement("canvas");
      return !!(elem.getContext && elem.getContext("2d"));
    },

    setGradient: function() {
      /*格式如下所示:
	{
  		0:'rgb(102, 255, 0)',
 	 	.5:'rgb(255, 170, 0)',
	  	1:'rgb(255, 0, 0)'
	}*/
      var gradient = {};
      var colors = document.querySelectorAll("input[type='color']");
      colors = [].slice.call(colors, 0);
      colors.forEach(function(ele) {
        gradient[ele.getAttribute("data-key")] = ele.value;
      });
      this.heatmapOverlay.setOptions({ gradient: gradient });
    },
    //是否显示热力图
    openHeatmap: function() {
      var _this = this;
      this.heatmapOverlay.setDataSet({ data: _this.devicePoint, max: 100 });

      this.heatmapOverlay.show();
    },
    //关闭热力图
    closeHeatmap: function() {
      this.heatmapOverlay.hide();
    },

    isEmptyObject: function(e) {
      var t;
      for (t in e) return !1;
      return !0;
    },
    ready: function() {
      setTimeout(function() {
        getBoundary();
      }, 100);
    }
  },

  mounted: function() {
    this.appKey = JSON.parse(localStorage.getItem("userInfo")).appKey;
    //挂载页面
    this.initDataAnalysisBaiduMap();
    // ************************热力图begin********************************//
    if (!this.isSupportCanvas()) {
      alert(
        "热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~"
      );
    }
    //详细的参数,可以查看heatmap.js的文档 https://github.com/pa7/heatmap.js/blob/master/README.md
    //参数说明如下:
    /* visible 热力图是否显示,默认为true
 * opacity 热力的透明度,1-100
 * radius 势力图的每个点的半径大小   
 * gradient  {JSON} 热力图的渐变区间 . gradient如下所示
 *	{
		.2:'rgb(0, 255, 255)',
		.5:'rgb(0, 110, 255)',
		.8:'rgb(100, 0, 255)'
	}
	其中 key 表示插值的位置, 0~1. 
	    value 为颜色值. 
 */
    this.heatmapOverlay = new BMapLib.HeatmapOverlay({ radius: 20 });
    window.AnalysisBaiduMap.addOverlay(this.heatmapOverlay);
    this.taskOfAddMarket = window.setInterval(() => {
      this.addMarketToMap("114.0832947235837", "32.16857465070465", "100");
    }, 4000);
  },
  destroyed: function() {
    //页面销毁
    window.clearInterval(this.taskOfAddMarket);
  }
};
</script>


